package console.gui.windows;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

/**
 *
 * @author Michael Hanns
 *
 */
public class CheckForUpdates extends javax.swing.JDialog {

    private final double version;

    /** Creates new form CheckForUpdates */
    public CheckForUpdates(java.awt.Frame parent, boolean modal, double version) {
        super(parent, modal);
        this.version = version;
        initComponents();

        Runnable task = new Runnable() {

            @Override
            public void run() {
                checkVersion();
            }
        };

        new Thread(task).start();
        progressBar.setVisible(false);
    }

    private void checkVersion() {
        double newVersion = version;
        try {
            URL whatismyip = new URL("http://servertools.whatisthynameadventurer.com/latestVersion.txt");
            InputStream stream = whatismyip.openStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(stream));

            // Get the number of servers from the first line of the reply
            String versLine = in.readLine();
            newVersion = Double.parseDouble(versLine);

            stream.close();
            in.close();

            if (newVersion > version) {
                latestVersionLabel.setText("There is a new version v" + newVersion
                        + " available for download! Click 'Download' to retrieve.");

                exeButton.setVisible(true);
            } else {
                latestVersionLabel.setText("Your WITNA software is up to date.");
            }

        } catch (IOException e) {
            //latestVersionLabel.setText("Error connecting to check updates.");
            // Fixed value for testing while the site is down
            latestVersionLabel.setText("There is a new version v" + newVersion
                    + " available for download! Click 'Download' to retrieve.");

            exeButton.setVisible(true);
        }
    }

    private void downloadFile() throws IOException {
        progressBar.setValue(0);
        String os = System.getProperty("os.name");
        progressBar.setVisible(true);
        latestVersionLabel.setText("Retrieving latest " + os + " build (connecting)...");

        String fileName = "WITNAWindows.exe";
        if (os.toLowerCase().startsWith(("win"))) {
            ;
        } else if (os.toLowerCase().startsWith("mac")) {
            fileName = "WITNAMac.dmg";
        } else if (os.toLowerCase().startsWith("linux")) {
            fileName = "WITNALinux.zip";
        }

        // TAKE NOTE! This is only downloading Windows Grep at the moment for
        // testing purposes. This will need fixing later.

        final URL file = new URL("http://www.wingrep.com/resources/binaries/WindowsGrep23.exe");

        int fileSize = Integer.parseInt(file.openConnection().getHeaderField("Content-Length"));

        final BufferedInputStream in = new BufferedInputStream(file.openStream());
        new File("downloads/").mkdir();
        FileOutputStream fos = new FileOutputStream("downloads/WindowsGrep23.exe");
        final BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);

        latestVersionLabel.setText("Retrieving latest " + os + " build...");
        byte[] data = new byte[8];
        int x = 0;
        double totalDownloaded = 0;
        int downPercent = 0;
        while ((x = in.read(data, 0, 8)) >= 0) {
            bout.write(data, 0, x);
            totalDownloaded += x;
            downPercent = (int) ((totalDownloaded / fileSize) * 100);
            progressBar.setValue(downPercent);
            latestVersionLabel.setText("Retrieving latest " + os + " build (" + downPercent + "%)...");
        }
        bout.close();
        in.close();

        latestVersionLabel.setText("Latest " + os + " build downloaded to WITNA/downloads/" + fileName + ".");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        closeButton = new javax.swing.JButton();
        exeButton = new javax.swing.JButton();
        latestVersionLabel = new javax.swing.JLabel();
        updatesHeaderLabel = new javax.swing.JLabel();
        currentVersionLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Check for updates");
        setLocationByPlatform(true);
        setResizable(false);

        closeButton.setText("Close");
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });

        exeButton.setText("Download");
        exeButton.setVisible(false);
        exeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exeButtonActionPerformed(evt);
            }
        });

        latestVersionLabel.setText("WITNA is checking the internet for updates, please be patient...");

        updatesHeaderLabel.setFont(new java.awt.Font("Tahoma", 1, 14));
        updatesHeaderLabel.setText("Check for updates");

        currentVersionLabel.setText("You are currently running WITNA v" + version + ".");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(progressBar, javax.swing.GroupLayout.DEFAULT_SIZE, 426, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(updatesHeaderLabel)
                                    .addComponent(latestVersionLabel)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(currentVersionLabel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 286, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(exeButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                        .addComponent(closeButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(updatesHeaderLabel)
                .addGap(18, 18, 18)
                .addComponent(currentVersionLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(latestVersionLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(closeButton)
                    .addComponent(exeButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void exeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exeButtonActionPerformed
        Runnable task = new Runnable() {

            @Override
            public void run() {
                try {
                    downloadFile();
                } catch (IOException ex) {
                    ex.printStackTrace();
                    latestVersionLabel.setText("Error retrieving latest " + System.getProperty("os.name") + " build...");
                }
            }
        };

        new Thread(task).start();
    }//GEN-LAST:event_exeButtonActionPerformed

    private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
        dispose();
    }//GEN-LAST:event_closeButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton closeButton;
    private javax.swing.JLabel currentVersionLabel;
    private javax.swing.JButton exeButton;
    private javax.swing.JLabel latestVersionLabel;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel updatesHeaderLabel;
    // End of variables declaration//GEN-END:variables
}
